package com.googlecode.scup.grammar.readers;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.CharArrayReader;
import java.util.ArrayList;
import java.util.List;

import com.googlecode.scup.grammar.Grammar;
import com.googlecode.scup.grammar.SimpleGrammar;
import com.googlecode.scup.grammar.grammarspart.Production;
import com.googlecode.scup.grammar.grammarspart.Rule;
import com.googlecode.scup.grammar.grammarspart.Symbol;

public class SimpleReader implements Reader {
	private BufferedReader buffer;
	private Grammar grammar;

	public SimpleReader(String path) throws IOException {
		buffer = new BufferedReader(new FileReader(path));

		String line;
		List<Rule> rules = new ArrayList<Rule>();
		while ((line = buffer.readLine()) != null) {
			String[] parts = line.split("->");
			Symbol base = new Symbol(parts[0].trim(), false);

			Rule rule = new Rule (base, new ArrayList<Production>());
			List<Symbol> symbols = new ArrayList<Symbol>();
			for (String sprod : parts[1].split("\\|")) {
				for (String prod : sprod.trim().split("\\s+")) {
					symbols.add(new Symbol(prod));
				}

				rule.addProduction(new Production(symbols));
				symbols = new ArrayList<Symbol>();
			}

			rules.add(rule);
		}

		grammar = new SimpleGrammar(rules);
	}

    public SimpleReader(char stream[]) throws IOException {
		buffer = new BufferedReader(new CharArrayReader(stream));

		String line;
		List<Rule> rules = new ArrayList<Rule>();
		while ((line = buffer.readLine()) != null) {
			String[] parts = line.split("->");
			Symbol base = new Symbol(parts[0].trim(), false);

			Rule rule = new Rule (base, new ArrayList<Production>());
			List<Symbol> symbols = new ArrayList<Symbol>();
			for (String sprod : parts[1].split("\\|")) {
				for (String prod : sprod.trim().split("\\s+")) {
					symbols.add(new Symbol(prod));
				}

				rule.addProduction(new Production(symbols));
				symbols = new ArrayList<Symbol>();
			}

			rules.add(rule);
		}

		grammar = new SimpleGrammar(rules);
	}

	public Grammar getGrammar() {
		return grammar;
	}
}
